package com.gxa.p2p.controller;

import com.alibaba.fastjson.JSON;
import com.gxa.p2p.businessExceptionCode.ErrorCode;
import com.gxa.p2p.exception.BusinessException;
import com.gxa.p2p.pojo.UserRegister;
import com.gxa.p2p.service.Userservice;
import com.gxa.p2p.service.impl.VerifyCodeServiceImpl;
import com.gxa.p2p.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 开启跨域访问
@CrossOrigin
@Controller//处理http请求
// 设置请求一级路径
@RequestMapping(value = "/User"/*,method =RequestMethod.GET*/)//配置url映射
@Api(value = "用户控制器", tags = "用户管理接口")
public class UserController {

    static String code;

    @Resource(name = "userService")
    Userservice userservice;
    @Resource
    VerifyCodeServiceImpl verifyCodeService;

    //登录操作 运用Token
    /**
     * 根据已经存在的用户名密码来实现登录操作
     *并且添加Token
     * @param
     * @return Map<String , Object> 封装成json的后端信息
     */

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    //这个注解表示你的返回值将存在responsebody中返回到前端，前端接收后会显示将数据到页面，页面不会跳转。
    @ApiOperation(value = "普通用户登录接口", httpMethod = "post", response = Map.class)
    //@RequestBody @RequestParam 获取请求参数的值
    public Map <String, Object> login(@RequestBody @ApiParam Map <String, Object> map,HttpServletRequest request) {
        HashMap <String, Object> hashMap = new HashMap <>();
        System.out.println(map);
        String r1 = MD5Creater.encode((String) map.get("password"));
        System.out.println(r1);
        UserRegister login = userservice.login((String) map.get("userName"), MD5Creater.encode((String) map.get("password")),request);
        if (login!=null) {
            hashMap.put("code", 0);
            hashMap.put("msg", "Success");
            hashMap.put("data",login);
            // Token认证相关代码
            JWTUtil jwtUtil = new JWTUtil();
            String userName = jwtUtil.createJWT((String) map.get("userName"), JSON.toJSONString(map), 15 * 60 * 1000, map);
            hashMap.put("token", userName);

        } else {
            throw new BusinessException(ErrorCode.FAILED);

        }
        return hashMap;


    }
    //注册操作
    /**
     * 根据需要输入的信息来提供普通用户注册
     *
     * @param
     * @return Map<String , Object> 封装成json的后端信息
     */
    @PostMapping("/reg")
    @ResponseBody
    //这个注解表示你的返回值将存在responsebody中返回到前端，前端接收后会显示将数据到页面，页面不会跳转。
    @ApiOperation(value = "普通用户注册接口", httpMethod = "post", response = Map.class)
    public Map <String, Object> save(@RequestBody @ApiParam HashMap<String,Object> map,HttpServletRequest request) {
        System.out.println(map.get("userRegister"));
        Object object = map.get("userRegister");
        System.out.println("===========================");
//        UserRegister userRegister= (UserRegister) object;
        //强转为对象类型
        UserRegister userRegister = JSON.parseObject(JSON.toJSONString(object), UserRegister.class);
        System.out.println("===========================");
        String code1 = (String) map.get("code");
        //对比验证码操作
        CodeUtil codeUtil=new CodeUtil();
        codeUtil.compare(code1,code);
        System.out.println(userRegister);
        //密码加密操作
        userRegister.setPassword(MD5Creater.encode(userRegister.getPassword()));
        System.out.println("++++++++++++++++++++++++++");
        boolean register = userservice.save(userRegister);
        MapUtil mapUtil = new MapUtil();
        if (register) {
            mapUtil.put("code", 0);
        mapUtil.put("msg", "添加成功");
    } else {
        throw new BusinessException(ErrorCode.FAILED);
    }
        return mapUtil.getMap();
    }
    //上传文件单独封装成方法。
    @RequestMapping(value = "upload")
    public Map <String, Object> uploadavatar(@RequestParam("file") List<MultipartFile> multipartFile, HttpServletRequest request) throws IOException {
        return (Map <String, Object>) FileUploadUtil.upload(multipartFile, request);
    }
    //发送短信
    /**
     * 根据传入的手机号来发送短信
     *
     * @param
     * @return Map<String , Object> 封装成json的后端信息
     */
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public MapUtil sendVerifyCode(@RequestBody  @ApiParam Map<String,String> phonemap, HttpServletRequest request) {

        String phoneNumber = phonemap.get("phoneNumber");
        System.out.println("接收到前端请求");
        MapUtil json = new MapUtil();
        try {
            verifyCodeService.sendVerifyCode(phoneNumber);
            code = String.valueOf(verifyCodeService.getCode());

            json.setCode(0);
            json.setMsg("验证码发送成功");
        } catch (Exception e) {
            json.setCode(1);
            json.setMsg(e.getMessage());
        }

        return json;
    }
    /**
     * 根据用户名,来判断普通用户的用户名注册是否重复
     *
     * @param
     * @return Map<String , Object> 封装成json的后端信息
     */

    @RequestMapping(value = "findUserName", method = RequestMethod.POST)
    @ResponseBody
    //这个注解表示你的返回值将存在responsebody中返回到前端，前端接收后会显示将数据到页面，页面不会跳转。
    @ApiOperation(value = "查询普通用户名是否重复接口", httpMethod = "post", response = Map.class)
    public Map <String, Object> findusername(@RequestParam(value = "userName") String username) {
        System.out.println(username);
        boolean byName = userservice.findByName(username);
        MapUtil mapUtil = new MapUtil();
        if (!byName) {
            mapUtil.put("code", 0);
            mapUtil.put("msg", "用户名可用，可以注册");
        } else {
            throw new BusinessException(ErrorCode.FAILED);
        }
        return mapUtil.getMap();

    }
    //通过id更改密码
    /**
     * 根据验证码验证后电话号码来更改密码的值
     *
     * @param
     * @return Map<String , Object> 封装成json的后端信息
     */
    @RequestMapping(value = "updateP", method = RequestMethod.POST)
    @ResponseBody
    //这个注解表示你的返回值将存在responsebody中返回到前端，前端接收后会显示将数据到页面，页面不会跳转。
    @ApiOperation(value = "普通用户根据电话号码更改密码接口", httpMethod = "post", response = Map.class)
    public Map <String, Object> updateP(@RequestBody Map<String,Object> map,HttpServletRequest request) {
            System.out.println(map.get("phonenumber"));
            System.out.println(map.get("password"));
            System.out.println(map.get("mapcode"));
            CodeUtil codeUtil=new CodeUtil();
            codeUtil.compare((String) map.get("mapcode"),code);

        boolean b = userservice.upDateP((String) map.get("phonenumber"),MD5Creater.encode((String) map.get("password")));

        System.out.println("jjjjjjjjjjjjjj "+ code);
        MapUtil mapUtil = new MapUtil();
        if (b) {
            mapUtil.put("code", 0);
            mapUtil.put("msg", "密码已经更改，请记住密码");

        } else {
            throw new BusinessException(ErrorCode.FAILED);
        }
        return mapUtil.getMap();

    }
    /**
     * 根据查询是否存在手机号,发送验证码
     *
     * @param
     * @return Map<String , Object> 封装成json的后端信息
     */
    @RequestMapping(value = "findPhoneNumber", method = RequestMethod.POST)
    @ResponseBody
    //这个注解表示你的返回值将存在responsebody中返回到前端，前端接收后会显示将数据到页面，页面不会跳转。
    @ApiOperation(value = "查询普通用户手机号是否重复并且发送验证码接口", httpMethod = "post", response = Map.class)
    public Map <String, Object> findphoneNumber(@RequestBody Map<String,String> phonenumber,HttpServletRequest request) {
            //System.out.println(phonenumber);
        String phonenumber1 = phonenumber.get("phonenumber");
        boolean phoneNumber = userservice.findPhoneNumber(phonenumber1);
        System.out.println(phonenumber1);
        MapUtil mapUtil = new MapUtil();
        if (phoneNumber) {
            mapUtil.put("code", 0);
            mapUtil.put("msg", "手机号正确");
          SendMessageUtil sendMessageUtil=new SendMessageUtil();
         sendMessageUtil.sendVerifyCode(phonenumber1);
            //创建session
//            request.getSession();
            // 保存code
            code=String.valueOf(sendMessageUtil.getcode());
//            request.getSession().setAttribute("code1", code);
        } else {
            throw new BusinessException(ErrorCode.FAILED);
        }
        return mapUtil.getMap();
    }

}